package cn.client.ui.view.main.mindfulness

import android.util.Log
import androidx.annotation.DrawableRes
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import cn.client.MainViewModel
import cn.client.R
import cn.client.data.remoteData.bean.AddMindfulnessLogBody
import cn.client.data.remoteData.bean.BuildGroupApply
import cn.client.data.remoteData.bean.DynamicData
import cn.client.data.remoteData.bean.EvaluateItem
import cn.client.data.remoteData.bean.GetEvaluate
import cn.client.data.remoteData.bean.InsertEvaluate
import cn.client.data.remoteData.bean.JoinGroup
import cn.client.data.remoteData.bean.MindfulnessGroup
import cn.client.data.remoteData.bean.MindfulnessLog
import cn.client.data.remoteData.bean.MindfulnessMedia
import cn.client.data.remoteData.bean.MindfulnessRequestWithUid
import cn.client.data.remoteData.bean.PageSelect
import cn.client.data.remoteData.bean.PageSelectByMid
import cn.client.data.remoteData.bean.PageSelectByUid
import cn.client.data.remoteData.bean.SelectUidAndMid
import cn.client.data.remoteData.repository.DynamicRepository
import cn.client.data.remoteData.repository.MindfulnessRepository
import cn.client.ui.view.main.dynamic.DynamicViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class MindfulnessViewModel @Inject constructor(
    private val repository: MindfulnessRepository,

    ) : ViewModel() {


    // 事件管道
    private val _pageEvents = Channel<PageEvent>(Channel.BUFFERED)

    // 可观察事件数据流
    val pageEvents = _pageEvents.receiveAsFlow()

    // 推荐列表
    private val _recommendMindfulness = MutableStateFlow<List<MindfulnessMedia>>(emptyList())
    val recommendMindfulness: StateFlow<List<MindfulnessMedia>> = _recommendMindfulness

    // 正念媒体资源列表
    private val _mindfulnessMedia = MutableStateFlow<List<MindfulnessMedia>>(emptyList())
    val mindfulnessMedia: StateFlow<List<MindfulnessMedia>> = _mindfulnessMedia

    // 正念收藏列表
    private val _mindfulnessCollect = MutableStateFlow<List<MindfulnessMedia>>(emptyList())
    val mindfulnessCollect: StateFlow<List<MindfulnessMedia>> = _mindfulnessCollect

    // 正念信息
    private val _mindfulnessInfo = MutableStateFlow<MindfulnessMedia?>(null)
    val mindfulnessInfo: StateFlow<MindfulnessMedia?> = _mindfulnessInfo

    // 正念团体列表
    private val _mindfulnessGroup = MutableStateFlow<List<MindfulnessGroup>>(emptyList())
    val mindfulnessGroup: StateFlow<List<MindfulnessGroup>> = _mindfulnessGroup

    // 已加入的正念团体列表
    private val _joinedGroupList = MutableStateFlow<List<JoinGroup>>(emptyList())
    val joinedGroupList: StateFlow<List<JoinGroup>> = _joinedGroupList

    // 打卡记录列表
    private val _mindfulnessLog = MutableStateFlow<List<MindfulnessLog>>(emptyList())
    val mindfulnessLog: StateFlow<List<MindfulnessLog>> = _mindfulnessLog

    // 收藏状态
    private val _isCollect = MutableStateFlow<Boolean>(false)
    val isCollect: StateFlow<Boolean> = _isCollect

    // 评分状态
    private val _isEvaluate = MutableStateFlow<Boolean>(false)
    val isEvaluate: StateFlow<Boolean> = _isEvaluate

    // 当前正念评分列表
    private val _evaluateList = MutableStateFlow<List<EvaluateItem>>(emptyList())
    val evaluateList: StateFlow<List<EvaluateItem>> = _evaluateList


    // 收集意图
    fun dispatch(intent: PageIntent) {
        when (intent) {
            is PageIntent.GetRecommendMindfulness -> getRecommendMindfulness(intent.pageSelect)
            is PageIntent.GetMindfulnessMediaList -> getMindfulnessMedaList(intent.pageSelect)
            is PageIntent.GetMindfulnessGroupList -> getMindfulnessGroupList(intent.pageSelect)
            is PageIntent.BuildMindfulnessGroup -> buildMindfulnessGroup(intent.groupApply)
            is PageIntent.GetJoinedGroupList -> getJoinedGroupList(intent.pageSelect)
            is PageIntent.GetMindfulnessInfo -> getMindfulnessInfo(intent.selectUidAndMid)
            is PageIntent.CollectMindfulness -> collectMindfulness(intent.collect)
            is PageIntent.UnCollectMindfulness -> unCollectMindfulness(intent.unCollect)
            is PageIntent.GetCollectMindfulnessList -> getCollectMindfulnessList(intent.uid)
            is PageIntent.GetEvaluate -> getEvaluate(intent.pageSelect)
            is PageIntent.GetEvaluateInfo -> getEvaluateInfo(intent.selectUidAndMid)
            is PageIntent.AddEvaluate -> addEvaluate(intent.evaluate)
            is PageIntent.UpdateEvaluate -> updateEvaluate(intent.evaluate)
            is PageIntent.AddLog -> addLog(intent.add)
            is PageIntent.GetLogList -> getLogList(intent.pageSelect)
            else -> Unit
        }
    }

    // 分页查询：（推荐）正念资源列表
    private fun getRecommendMindfulness(pageSelect: PageSelectByUid){
        viewModelScope.launch {
            try {
                val res = repository.getMediaListByUid(pageSelect)
                if (res.code == 200) {
                    _recommendMindfulness.value = res.data!!
                } else {
                    _pageEvents.send(PageEvent.Error(res.msg))
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("MindfulnessViewModel", "程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }

    // 处理意图-分页查询：正念团体列表
    private fun getMindfulnessGroupList(pageSelect: PageSelect) {
        viewModelScope.launch {
            try {
                val res = repository.getGroupList(pageSelect)
                if (res.code == 200) {
                    _mindfulnessGroup.value = res.data ?: emptyList()
                } else {
                    _pageEvents.send(PageEvent.Error(res.msg))
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("MindfulnessViewModel", "程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }

    // 处理意图-创建正念团体
    private fun buildMindfulnessGroup(groupApply: BuildGroupApply){
        viewModelScope.launch {
            try {
                val res = repository.buildGroup(groupApply)
                if (res.code == 200) {
                    _pageEvents.send(PageEvent.Success(res.msg))
                } else {
                    _pageEvents.send(PageEvent.Error(res.msg))
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("MindfulnessViewModel", "程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }

    // 处理意图-分页查询：获取已加入的正念团体列表
    private fun getJoinedGroupList(pageSelect: PageSelectByUid){
        viewModelScope.launch {
            try {
                val res = repository.getJoinGroupList(pageSelect)
                if (res.code == 200) {
                    _joinedGroupList.value = res.data ?: emptyList()
                } else {
                    _pageEvents.send(PageEvent.Error(res.msg))
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("MindfulnessViewModel", "程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }

    // 处理意图-获取正念信息
    private fun getMindfulnessInfo(selectUidAndMid: SelectUidAndMid) {
        viewModelScope.launch {
            try {
                val res = repository.getMediaInfo(selectUidAndMid)
                if (res.code == 200) {
                    _mindfulnessInfo.value = res.data
                    (res.data!!.isCollect != 0).also { _isCollect.value = it }
                    (res.data!!.isEvaluate != 0).also { _isEvaluate.value = it }
                } else {
                    _pageEvents.send(PageEvent.Error(res.msg))
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("MindfulnessViewModel", "程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }

    // 处理意图-分页查询：正念资源列表
    private fun getMindfulnessMedaList(pageSelect: PageSelect) {
        viewModelScope.launch {
            try {
                val res = repository.getMediaList(pageSelect)
                if (res.code == 200) {
                    _mindfulnessMedia.value = res.data ?: emptyList()
                } else {
                    _pageEvents.send(PageEvent.Error(res.msg))
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("MindfulnessViewModel", "程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }

    // 处理意图-收藏正念
    private fun collectMindfulness(collect: MindfulnessRequestWithUid) {
        viewModelScope.launch {
            try {
                val res = repository.collectMindfulness(collect)
                if (res.code == 200) {
                    _pageEvents.send(PageEvent.Success(res.msg))
                    _isCollect.value = true
                } else {
                    _pageEvents.send(PageEvent.Error(res.msg))
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("MindfulnessViewModel", "程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }

    // 处理意图-取消收藏正念
    private fun unCollectMindfulness(unCollect: MindfulnessRequestWithUid){
        viewModelScope.launch {
            try {
                val res = repository.unCollectMindfulness(unCollect)
                if (res.code == 200) {
                    _isCollect.value = false
                } else {
                    _pageEvents.send(PageEvent.Error(res.msg))
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("MindfulnessViewModel", "程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }

    // 处理意图-查看收藏
    private fun getCollectMindfulnessList(uid: Int) {
        viewModelScope.launch {
            try {
                val res = repository.selectCollectMindfulness(uid)
                if (res.code == 200) {
                    _mindfulnessCollect.value = res.data!!
                } else {
                    _pageEvents.send(PageEvent.Error(res.msg))
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("MindfulnessViewModel", "程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }

    // 处理意图-查看评分列表
    private fun getEvaluate(pageSelect: PageSelectByMid){
        viewModelScope.launch {
            try {
                val res = repository.getEvaluateInMindfulness(pageSelect)
                if (res.code == 200) {
                    _evaluateList.value = res.data?.takeIf { it.isNotEmpty() } ?: _evaluateList.value
                } else {
                    _pageEvents.send(PageEvent.Error(res.msg))
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("MindfulnessViewModel", "程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }

    // 处理意图-查看正念评分信息
    private fun getEvaluateInfo(selectUidAndMid: SelectUidAndMid){
        viewModelScope.launch {
            try {
                val res = repository.getEvaluateInfo(selectUidAndMid)
                if (res.code == 200) {
                    _pageEvents.send(PageEvent.ResEvaluate(res.data))
                    if (res.data!=null){
                        _isEvaluate.value = true
                    }
                } else {
                    _pageEvents.send(PageEvent.Error(res.msg))
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("MindfulnessViewModel", "程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }

    // 处理意图-新增评分
    private fun addEvaluate(evaluate: InsertEvaluate){
        viewModelScope.launch {
            try {
                val res = repository.addEvaluateInMindfulness(evaluate)
                if (res.code == 200) {
                    _pageEvents.send(PageEvent.Success(res.msg))
                } else {
                    _pageEvents.send(PageEvent.Error(res.msg))
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("MindfulnessViewModel", "程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }

    // 处理意图-修改评分
    private fun updateEvaluate(evaluate: InsertEvaluate){
        viewModelScope.launch {
            try {
                val res = repository.updateEvaluateInMindfulness(evaluate)
                if (res.code == 200) {
                    _pageEvents.send(PageEvent.Success(res.msg))
                } else {
                    _pageEvents.send(PageEvent.Error(res.msg))
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("MindfulnessViewModel", "程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }

    // 处理意图-新增打卡
    private fun addLog(add: AddMindfulnessLogBody){
        viewModelScope.launch {
            try {
                val res = repository.addMindfulnessLog(add)
                if (res.code == 200) {
                    _pageEvents.send(PageEvent.Success(res.msg))
                } else {
                    _pageEvents.send(PageEvent.Error(res.msg))
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("MindfulnessViewModel", "程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }

    // 处理意图-获取打卡列表
    private fun getLogList(pageSelect: PageSelectByUid){
        viewModelScope.launch {
            try {
                val res = repository.getMindfulnessLogList(pageSelect)
                if (res.code == 200) {
                    _mindfulnessLog.value = res.data!!
                } else {
                    _pageEvents.send(PageEvent.Error(res.msg))
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("MindfulnessViewModel", "程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }

    // 意图集
    sealed class PageIntent {
        data class GetMindfulnessMediaList(val pageSelect: PageSelect) :
            PageIntent()  // 分页查询：正念资源列表

        data class GetRecommendMindfulness(val pageSelect: PageSelectByUid) :
            PageIntent()  // 分页查询：（推荐）正念资源列表

        data class GetMindfulnessInfo(val selectUidAndMid: SelectUidAndMid) : PageIntent() // 查询正念信息
        data class GetMindfulnessGroupList(val pageSelect: PageSelect) :
            PageIntent()  // 分页查询：正念团体列表

        data class BuildMindfulnessGroup(val groupApply: BuildGroupApply): PageIntent()   //正念团体创建申请

        data class GetJoinedGroupList(val pageSelect: PageSelectByUid): PageIntent()  // 获取已加入的正念团体列表

        data class CollectMindfulness(val collect: MindfulnessRequestWithUid): PageIntent()  // 收藏正念
        data class UnCollectMindfulness(val unCollect: MindfulnessRequestWithUid): PageIntent()     // 取消收藏正念

        data class GetCollectMindfulnessList(val uid: Int) : PageIntent()  // 查看收藏正念

        data class GetEvaluateInfo(val selectUidAndMid: SelectUidAndMid): PageIntent()  // 查看评分信息
        data class GetEvaluate(val pageSelect: PageSelectByMid): PageIntent()  // 查看评分列表

        data class AddEvaluate(val evaluate: InsertEvaluate): PageIntent()  // 新增评分列表
        data class UpdateEvaluate(val evaluate: InsertEvaluate): PageIntent()  // 修改评分列表

        data class AddLog(val add: AddMindfulnessLogBody): PageIntent()  // 新增打卡
        data class GetLogList(val pageSelect: PageSelectByUid): PageIntent()  // 获取打卡列表

    }

    // 事件集
    sealed class PageEvent {
        data class Success(val msg: String) : PageEvent()
        data class Error(val error: String) : PageEvent()

        data class ResEvaluate(val evaluate: GetEvaluate?) : PageEvent()  // 返回的评分信息

    }

}